<?php
/**
 * Created by PhpStorm.
 * User: Caoyixian
 * Date: 2017/7/25
 * Time: 下午 3:50
 */


use Workerman\Worker;
use \Workerman\Lib\Timer;
include_once __DIR__.DIRECTORY_SEPARATOR.'Autoloader.php';

$uids = 0;
$worker = null;
$worker = new Worker('websocket://0.0.0.0:50009');

    $worker->onWorkerStart = function($worker)
    {
        global $Logdb;
        $dbclass =  __DIR__.DIRECTORY_SEPARATOR.'mysql'.DIRECTORY_SEPARATOR.'Logdb.php';
        if(file_exists($dbclass)){
            include_once $dbclass;
            $Logdb = new Logdb();
        }
       // $time_interval = 2.5;
        Timer::add(60, 'update_run_log', array(time()),true);
        echo "Worker starting...\n";
    };

// 普通的函数
    function update_run_log($current_time)
    {
        global $Logdb;
        $Logdb->save_run_log();
    }

    $worker->onConnect = function($connection)
    {
        global $uids;
        //$connection->maxSendBufferSize = 102400;//设置当前链接缓存区大小1M
        $connection->uid = ++$uids;
        //$messgae =  "new connection from client : " . $connection->uid . "\n";
        //$connection->send($messgae);
    };

    $worker->onClose = function($connection)
    {
        //删除当前客户端链接;
        global $Logdb;
        $Logdb->destroy_token_connnection_id($connection->uid);

    };

    $worker->onMessage = function($connection, $data)
    {
        //echo "收到客户端信息".$data;
        //回复当前连接信息h
        //$connection->send($data."已经收到");
        //解析来源
        $data =  json_decode($data,true);
        $token = isset($data['token']) ? $data['token'] : '';
        $site_id = isset($data['site_id']) ? $data['site_id'] : '';
        $uid = isset($data['uid']) ? $data['uid'] : '';//发送用户id
        $nickname = isset($data['nickname']) ? $data['nickname'] : '';//昵称
        $event = isset($data['event']) ? $data['event'] : '';//string,file
        $content = isset($data['content']) ? $data['content'] : '';//文本内容
        if(!$token || !$uid || !$event || !$content || !$site_id || !$nickname){
            $connection->send(json_encode(['ret'=>400,'msg'=>'参数不完整','test'=>$data],JSON_UNESCAPED_UNICODE));
            return;
        }
//        $type = stripos($content,'http')===0 ? 1 : 0;先临时处理下,等会再用正则匹配
        $type = (preg_match("/^(http|https){1}(.*?)+(\\.png|\\.jpg|\\.gif){1}$/i",$content)) ? 1 : 0;
        if($type){
            $data['type'] = 'image';
        }else{
            $data['type'] = 'text';
        }
        //向所有客户端广播
        global $worker;
        global $Logdb;
        //重写事件绑定
        if($Logdb->is_site_service($token)){
            $event = $data['event'] = 'reply';
            //绑定客户端token到当前线程ID
            $Logdb->binding_token_connnection_id($token,-1,$connection->uid,$site_id,$nickname);
        }else{
            $event = $data['event'] = 'query';
            //绑定客户端token到当前线程ID
            $Logdb->binding_token_connnection_id($token,$uid,$connection->uid,$site_id,$nickname);
        }

        //初始化处理
        if($content == 'init'){
            $connection->send(json_encode(['ret'=>0,'data'=>['init'=>'success','event'=>$event]],JSON_UNESCAPED_UNICODE));
            return;
        }


         if($event=='query'){
             //保存聊天记录
             $ret = $Logdb->save_log($data);
             //客户留言，查询客服是否在线，如果在线推送消息给他，否则保存聊天记录到数据库
             if($connection_id = $Logdb->get_site_service_status($site_id)){
                 //发送信息到客服
                 $conn = $worker->connections[$connection_id];
                 $data['send_time'] = date("Y-m-d H:i:s");
                 $conn->send(json_encode(['ret'=>0,'data'=>$data],JSON_UNESCAPED_UNICODE));

             }else{
                 //提示客服不在线
                 $connection->send(json_encode(['ret'=>400,'msg'=>'当前客服不在线','send_time'=>date("Y-m-d H:i:s")],JSON_UNESCAPED_UNICODE));
             }

         }elseif($event=='reply'){
             //保存聊天记录
             $ret = $Logdb->save_log($data);
             //客服回答  查询用户是否在线，如果在线摄像头消息给他，否则保存聊天记录到数据库
             $client_info = $Logdb->get_client_info($data['uid']);
              if($client_info){
                  unset($data['uid']);
                  unset($data['token']);
                  $conn = $worker->connections[$client_info->connection_id];
                  $data['send_time'] = date("Y-m-d H:i:s");
                  $conn->send(json_encode(['ret'=>0,'data'=>$data],JSON_UNESCAPED_UNICODE));
              }else{
                  $connection->send(json_encode(['ret'=>400,'msg'=>'用户不在线','data'=>['uid'=>$uid],'msg'=>'用户不在线','send_time'=>date("Y-m-d H:i:s")],JSON_UNESCAPED_UNICODE));
              }

         }else{
             //
             $connection->send(json_encode(['ret'=>500,'msg'=>'服务器异常'],JSON_UNESCAPED_UNICODE));

         }



        /***
        foreach($worker->connections as $conn) {
        $a = $worker->connections[1];
        $a->send('aaaa');
            $conn->send(json_encode($data)."\r\n");
        }
        ***/

    };
    //防止缓存溢出
    $worker->onBufferFull = function($connection)
    {
        echo "bufferFull and do not send again\n";
    };

    $worker->onBufferDrain = function($connection)
    {
        echo "buffer drain and continue send\n";
    };

// 运行worker
Worker::runAll();

